import React, { useState, useEffect } from 'react';
import { createForm } from 'rc-form';
import FormControl from '@material-ui/core/FormControl';
import FormLabel from '@material-ui/core/FormLabel';
import Alert from '@/components/Alert';
import Typography from '@material-ui/core/Typography';

import Box from '@material-ui/core/Box';
import LinearProgress from '@material-ui/core/LinearProgress';
import ScaleToolbar from '@/pages/scale/components/ScaleToolbar';
import Factory from '@/pages/scale/components/field/Factory';

function ScaleAnswer(props) {
  const {
    form,
    submit,
    current = 0,
    code,
    model,
    model: { scaleQuestions = [] },
    renderQuestionContent: RenderQuestionContent,
    renderOptionContent: RenderOptionContent,
    onChange,
    sortOptions,
    values = {},
    config = {},
  } = props;

  const { getFieldDecorator, getFieldError } = form;

  const [currentStep, setCurrentStep] = useState(0);
  const [answerValues, setAnswerValues] = useState(values);
  const [answerNo, setAnswerNo] = useState(0);

  const changeStep = nextStep => {
    setCurrentStep(nextStep);
  };

  const skipStep = nextStep => {
    setCurrentStep(nextStep);
    if (onChange) {
      onChange({
        type: 'SKIP',
        step: nextStep,
      });
    }
  };

  const changeAnswer = (questionNo, value) => {
    const v = { ...answerValues };
    const normalise = No => ((No - 0) * 100) / (scaleQuestions.length - 0);
    v[questionNo] = value;

    setAnswerValues(v);
    setAnswerNo(normalise(questionNo));

    if (onChange) {
      onChange({
        type: 'ANSWER',
        no: currentStep + 1,
        value,
        values: v,
        step: currentStep,
        changeStep,
        questionSize: scaleQuestions.length,
        setAnswerValues,
      });
    }
  };

  const renderQuestionContent = ({ questionNo, questionData, questionContent }) => {
    if (questionData === 'IMAGE') {
      // eslint-disable-next-line jsx-a11y/alt-text
      return <img src={`/images/scale/${code}/${questionContent}`} />;
    }

    return (
      <Typography>
        {questionNo}.{questionContent}
      </Typography>
    );
  };

  const questions = () => {
    model.scaleQuestions.sort((a, b) => a.questionNo * 1 - b.questionNo * 1);

    const question = model.scaleQuestions[currentStep];

    if (sortOptions) {
      sortOptions(question.scaleOptions);
    } else {
      question.scaleOptions.sort((a, b) => a.option * 1 - b.option * 1);
    }

    const { questionType, scaleOptions } = question;

    const errors = getFieldError(`${question.questionNo}`);

    return [
      <div key={question.questionNo}>
        <div>
          <FormControl
            style={{ width: '100%', cursor: 'pointer' }}
            key={question.questionNo}
            component="fieldset"
          >
            <div
              style={{
                margin: '20px 20px 0px 20px',
              }}
            >
              <FormLabel style={{ lineHeight: '30px' }} component="legend" focused={false}>
                {RenderQuestionContent ? (
                  <RenderQuestionContent model={model} question={question} />
                ) : (
                  renderQuestionContent(question)
                )}
              </FormLabel>
            </div>

            {getFieldDecorator(`${question.questionNo}`, {
              initialValue:
                answerValues[`${question.questionNo}`] || answerValues[question.questionNo] || '',
              onChange: e => {
                if (e.target) {
                  changeAnswer(question.questionNo, e.target.value);
                } else {
                  changeAnswer(question.questionNo, e);
                }
              },
              rules: [{ required: true, message: '这道题必须回答' }],
            })(
              <Factory
                code={code}
                questionType={questionType}
                scaleOptions={scaleOptions}
                RenderOptionContent={RenderOptionContent}
              />
            )}
          </FormControl>
        </div>
        {errors ? <Alert type="error">{errors.join(',')}</Alert> : null}
      </div>,
    ];
  };

  /**
   * 進度條.預設為不顯示
   */
  const supportProgress = () => {
    const { progress = false } = config;
    if (progress) {
      return (
        <Box display="flex" alignItems="center">
          <Box width="100%" mr={1}>
            <LinearProgress variant="determinate" value={answerNo} />
          </Box>
          <Box minWidth={50}>
            <Typography variant="body2" color="textSecondary">
              {Object.keys(answerValues || {}).length} / {scaleQuestions.length}
            </Typography>
          </Box>
        </Box>
      );
    }
  };

  useEffect(() => {
    if (current !== 0) {
      skipStep(current);
    }
  }, []);

  console.log('answerValues:',answerValues);

  return (
    <div>
      <div style={{ margin: 10 }}>{supportProgress()}</div>
      <div style={{ paddingBottom: '10px', margin: 10, backgroundColor: 'white' }}>
        {questions()}
      </div>
      <ScaleToolbar
        form={form}
        submit={submit}
        answerValues={answerValues}
        scaleQuestions={scaleQuestions}
        changeStep={changeStep}
        currentStep={currentStep}
      />
    </div>
  );
}

export default createForm({})(ScaleAnswer);
